/**
 * @Author: wsl
 * @Date: 2022/2/15 9:58
 */

package com.wsl.service.tag;


import com.alibaba.fastjson.JSONArray;
import com.wsl.dao.TagDao;
import com.wsl.entity.blog.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class TagService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    TagDao tagDao;


    /*获取全部的tag标签*/
    public JSONArray getTagAll() {
        JSONArray jsonArray = new JSONArray();

        String sql = "select * from t_tag";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);

        jsonArray.add(maps);
        return jsonArray;
    }


    @Transactional
    public int setTag(String tagName) {
        try {
            /*查询是否存在*/
            String sqlQueryName = "select t.name from t_tag t where name = '" + tagName + "'";
            List<String> list = jdbcTemplate.queryForList(sqlQueryName, String.class);
            if (list.size() > 0) {
                return 0;
            }
            /*查询最大的id*/
            String sqlMaxId = "select Max(id) from t_tag";
            Long s = jdbcTemplate.queryForObject(sqlMaxId, Long.class);
            tagDao.save(new Tag(s + 1, tagName));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
        return 1;
    }

    /*删除标签*/
    @Transactional
    public int delTag(String name) {

        Tag tag = tagDao.findByName(name);

        try {
            if (tag == null) {
                return 0;
            }
            return tagDao.deleteByName(name);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }





}